/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.unice.servlet;

import att.grappa.Element;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 *
 * @author ED
 */
public class FonctionServlet1 extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public String inscriptionMembre(HttpServletRequest request){
        String pseudo = request.getParameter("pseudo");
        String password = request.getParameter("password");
        String mail = request.getParameter("mail");
        String reponse="";
                        
           reponse=AjouterUtilisateur.newUser(request);


            System.out.println("ouverture");


        return reponse;
    }
     public String connection(HttpServletRequest request){
        String pseudo = request.getParameter("pseudo");
        String password = request.getParameter("password");
        //String mail = request.getParameter("mail");
        String reponse="";

                 lectureXML lecteur = new lectureXML();
                 lecteur.ouverture("users.xml");
                 int reponseVerification = lecteur.verifierIdentification(pseudo,password);

                  if(reponseVerification==100){
                    reponse=" Utilisateur Inexistant";
                    reponse="100";
                 } else if (reponseVerification== 1) {
                      reponse=" Utilisateur Existant Mais Password Faut";
                      reponse="1";

                 }
                 else if (reponseVerification== 2) {
                    HttpSession session = request.getSession(true);
                   
                    Utilisateur user = new Utilisateur();

                    user.setLogin(request.getParameter("pseudo"));
                    user.setNom(lecteur.getNom());
                    user.setPrenom(lecteur.getPrenom());
                    user.setEmail(lecteur.getEmail());
                    user.setPassword(request.getParameter("password"));

                    session.putValue("user", user);
                    session.putValue("pseudo",user.getLogin());
                    

                    
                    session.setMaxInactiveInterval(3600);






                    reponse="Identification réussie : "+user.getLogin();
                    reponse="2";
                    }
                   else if (reponseVerification== 3) {
                     // reponse="password incorrect";
                       reponse="3";

                     } else {
                     reponse="vide";

            }




            System.out.println("connection");


        return reponse;
    }
     public String deconnection(HttpServletRequest request){
            System.out.println("deconnection");
         String reponse="vide";
         HttpSession session = request.getSession(true);

         if (session.getValue("user")!=null){
             session.invalidate();
             reponse="deconnection";
         }

         return reponse;

     }

    private String chargementPlayList(HttpServletRequest request) {

        String reponse="";

        String fileName = request.getSession(true).getAttribute("pseudo")+"PersonalPlayList000.xml";
        System.out.println("sauvPlayList : session : "+ request.getSession(true).getAttribute("pseudo"));
        File file = new File(fileName); // Le fichier XML
        // Si le fichier n'existe pas, on redirige l'utilisateur vers la page d'index qui s'occupera de la création du fichier xml
            if(!file.exists()){
                System.out.println("sauvPlayList : le fichier n'existe pas");
                JDOM.creerFilePlayList(fileName);
            }

          lectureXML lecteur = new lectureXML(); // Notre lecteur xml

          lecteur.ouverture(fileName); // Récupération de la racine et des documents/

          System.out.println("sauvPlayList : ouverture du fichier");
          org.jdom.Element racine = lectureXML.getRacine();
          org.jdom.Document document =lectureXML.getDocument();
          JDOMList initDoc=new JDOMList();
          initDoc.setDocument(document);
          initDoc.setRacine(racine);
          String namePlayList=request.getParameter("namePlayList");
          reponse= JDOMList.getPlayListString(namePlayList);





        return reponse;
    }

private String listPlayList(HttpServletRequest request){
    this.initialisationFilePlaylist(request);
    String fileName = request.getSession(true).getAttribute("pseudo")+"PersonalPlayList000.xml";


    lectureXML lecteur = new lectureXML(); // Notre lecteur xml

    lecteur.ouverture(fileName); // Récupération de la racine et des documents/

    System.out.println("sauvPlayList : ouverture du fichier");
    org.jdom.Element racine = lectureXML.getRacine();
    org.jdom.Document document =lectureXML.getDocument();
    JDOMList.racine=racine;
    JDOMList.document=document;


String reponse="";
     Iterator i =   JDOMList.getListPlayList(fileName).iterator();
     if (JDOMList.getListPlayList(fileName).size()>0){
    reponse="<select name='listPlayList' id='listPlayList'>";
     while(i.hasNext())
            {
                String nomPlaylist = (String)i.next();
                reponse+="<option name="+nomPlaylist+">"+nomPlaylist+"</option>";
            }
     reponse+="</select>";
     }else{
         reponse="Aucune PlayList enregistrer";
     }

     return reponse;





}

private void initialisationFilePlaylist(HttpServletRequest request){
    String fileName = request.getSession(true).getAttribute("pseudo")+"PersonalPlayList000.xml";
        System.out.println("sauvPlayList : session : "+ request.getSession(true).getAttribute("pseudo"));
        File file = new File(fileName); // Le fichier XML
        // Si le fichier n'existe pas, on redirige l'utilisateur vers la page d'index qui s'occupera de la création du fichier xml
            if(!file.exists()){
                System.out.println("sauvPlayList : le fichier n'existe pas");
                JDOM.creerFilePlayList(fileName);
            }
}

    private String sauvPlaylist(HttpServletRequest request) {
      

        String fileName = request.getSession(true).getAttribute("pseudo")+"PersonalPlayList000.xml";
        System.out.println("sauvPlayList : session : "+ request.getSession(true).getAttribute("pseudo"));
        File file = new File(fileName); // Le fichier XML
        // Si le fichier n'existe pas, on redirige l'utilisateur vers la page d'index qui s'occupera de la création du fichier xml
            if(!file.exists()){
                System.out.println("sauvPlayList : le fichier n'existe pas");
                JDOM.creerFilePlayList(fileName);
            }
           
          lectureXML lecteur = new lectureXML(); // Notre lecteur xml

          lecteur.ouverture(fileName); // Récupération de la racine et des documents/

          System.out.println("sauvPlayList : ouverture du fichier");
          org.jdom.Element racine = lectureXML.getRacine();          
          org.jdom.Document document =lectureXML.getDocument();
          JDOMList.document=document;
          JDOMList.racine=racine;

       String reponse="";
       String[] liste=request.getParameter("liste_videos").split(",");
       String namePlayList=request.getParameter("namePlayList");
       
//         JDOMList.ajouterPlayList(racine, document, namePlayList, fileName);
       
        System.out.println("sauvPlayList : namePlayList : "+namePlayList);
        reponse+="<br/><br/><br/>";
        int position=0;
        
        ArrayList<String> idVideoAjouter=new ArrayList<String>();
        if (JDOMList.getPlayList(namePlayList)!=null){
            System.out.println("suppression de la playList");
           JDOMList.getPlayList(namePlayList).removeContent();

            JDOMList.enregistre(fileName);
        }
        

        for(String s:liste) {
            String location, image, title;
            String[] video=s.split("~");
            if (video.length==3){
                image = video[0];
                location = video[1];
                title = video[2];
                position++;

                idVideoAjouter.add(video[1]);

                JDOMList.ajouterVideo(racine, document,namePlayList,image, location, title,position,fileName);
            }


            reponse+="<br/>";

        }
        
   
        reponse+= file.getAbsolutePath();







       

       return reponse;


    }
 private String verifSession(HttpServletRequest request) {
       String reponse="";
       HttpSession session = request.getSession(true);
       if (session.getValue("user")!=null){
           System.out.println("reponse : "+session.getAttribute("pseudo"));
           reponse=(String)session.getAttribute("pseudo");
       }else{
           reponse="-1";
       }

        return reponse;
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String reponse="";
         Map<String, String[]> params = request.getParameterMap();

         if (params.isEmpty()){

         }else{
             String fonction=request.getParameter("fonction");
             System.out.println("fonction : "+fonction);
             if (! fonction.equals("")){


                 switch(Integer.parseInt(fonction)){
                     case 1: // inscription d'un membre
                        reponse=inscriptionMembre(request);

                         break;
                     case 2 : // connection d'un membre
                         reponse=connection(request);
                         break;

                     case 3 : // connection d'un membre
                         reponse=deconnection(request);
                         break;
                      case 4 : // verification de session Youn'rs
                         reponse=verifSession(request);
                         break;
                      case 5 : // sauvegarde de playlist
                         reponse=sauvPlaylist(request);
                         break;
                      case 6 : // Chargement PlayList
                         reponse=chargementPlayList(request);
                        break;
                        
                        case 7 : // Liste de PlayList
                         reponse=listPlayList(request);
                        break;

                     default : reponse="fonction Inconnu"; break;
                 }
             }
         }

        try {

             response.setHeader("Cache-Control", "no-cache");
             response.getWriter().write(reponse);
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet FonctionServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet FonctionServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");

*/




        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

   

}
